<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\model\CrontabTaskModel;
use app\service\analysis\stat\KsVideoService;
use think\console\Input;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class ClientKsUserStatWork extends BaseWork implements DailyStatWork
{
    public ?string $tag = null;

    public function setTag($tag = null): bool
    {
        if (! is_null($tag)) {
            $this->tag = $tag;
        }
        return true;
    }

    public function getTag(): ?string
    {
        return strval($this->tag);
    }

    public function getCommandName(): string
    {
        return $this->getName();
    }

    /**
     * 获取定时任务.
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCrontabTaskInfo(): CrontabTaskModel
    {
        $where = [
            ['task_name', '=', $this->getName()],
            ['tag', '=', $this->getTag()],
        ];

        $obj = new CrontabTaskModel();
        $model = $obj->where($where)->field(true)->find();
        return $model instanceof CrontabTaskModel ? $model : $obj;
    }

    protected function configure()
    {
        // 指令配置
        $this->setName('client_ks_user_stat_work')
            ->setDescription('磁力引擎-客户维度快手视频消耗统计任务')
            ->setHelp('php think client_ks_user_stat_work');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');

        $output->writeln('=======磁力引擎快手视频消耗统计任务开始' . date('Y-m-d H:i:s', time()) . '=======');

        $res = KsVideoService::ClientUserCostStat();
        if (! $res) {
            $output->writeln('=======磁力引擎快手视频消耗统计任务失败' . date('Y-m-d H:i:s', time()) . '=======');
            return false;
        }
        $output->writeln('=======磁力引擎快手视频消耗统计任务结束' . date('Y-m-d H:i:s', time()) . '=======');
    }
}
